//判断是否是自己或者子元素
jQuery.fn.isChildAndSelfOf=function(b) {
    return(this.closest(b).length > 0);
};
//浏览器判断
var browser = {
    versions: function() {
        var u = navigator.userAgent, app = navigator.appVersion;
        return {//移动终端浏览器版本信息
            trident: u.indexOf('Trident') > -1, //IE内核
            presto: u.indexOf('Presto') > -1, //opera内核
            webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
            gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
            mobile: !!u.match(/AppleWebKit.*Mobile.*/) || !!app.match(/AppleWebKit/), //是否为移动终端
            ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
            android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
            iPhone: u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否为iPhone或者QQHD浏览器
            iPad: u.indexOf('iPad') > -1, //是否iPad
            webApp: u.indexOf('Safari') == -1 //是否web应该程序，没有头部与底部
        };
    }(),
    language: (navigator.browserLanguage || navigator.language).toLowerCase()
};
var demo={
    init:function(){
        this.reset();
        this.page();
        this.links();
        this.setPageLayer();
        this.showLinks();
        this.dialogLinks();
    },
    page:function(){
        var self=this;
        var tapCount=0;
        $(document).on('mousemove touchmove','.et-page',function(e){
            e.preventDefault();
        });
		$(document).hammer().on('tap','#dialogInput',function(e){
		    $("#dialogInput").hide();
		});
		$(document).hammer().on('tap','#userName2',function(e){
		    return false;
		});
		$(document).hammer().on('tap','#dialogInput a',function(e){
			$("#dialogInput").hide();
		    return false;
		});
        $(document).on("release",".et-page",function(e){
            tapCount=0;
        });
        $(document).hammer().on('dragleft dragright dragdown dragup','.et-page',function(e){
            var gesture=e.type;
            $(this).find(".page_gesture").each(function(){
                var thisGesture=$(this).attr('page-gesture');
                var page=$(this).attr('gesture-target');
                var $picturePage=$('#picture_'+page);
                var title=$picturePage.attr("data-title");
                if(!title){
                    title=$picturePage.attr("title");
                }
                if(gesture==thisGesture){
                    switch(gesture){
                        case 'dragleft':
                            self._set('moveFromRight','moveToLeftEasing ontop');
                            break;
                        case 'dragright':
                            self._set('moveFromLeft','moveToRightEasing ontop');
                            break;
                        case 'dragdown':
                            self._set('moveFromTop','moveToBottomEasing ontop');
                            break;
                        case 'dragup':
                            self._set('moveFromBottom','moveToTopEasing ontop');
                            break;
                        default :
                            return false;
                            break;
                    }
                    if(tapCount<2){
                        PageTransitions.initPage($picturePage);
                        $picturePage.find("img").each(function(){
                            $(this).attr("src",$(this).attr("ajax-src"));
                        });
                        self.isRememberHistory(title);
                    }
                }
            });
        });
    },
    isRememberHistory:function(title){
        if(/ MicroMessenger\//.test(navigator.userAgent)){

        }else if(/ QQ\//.test(navigator.userAgent)){

        }else{
            window.history.pushState("","","#"+title);
        }
    },
    links:function(){
        var self=this;
        $(document).on('mousemove touchmove','.et-page',function(e){
            e.preventDefault();
        });
        $(document).on("touchstart",'.link',function(e){
            $(this).addClass("active");
        });
        $(document).on("touchend",'.link',function(e){
            $(this).removeClass("active");
        });
        $(document).hammer().on("tap",".dialog_box",function(e){
            $(".dialog_box").hide();
            $(".link__dialog").hide();
            return false;
        });
        $(document).hammer().on("tap",".link__dialog",function(e){
            return false;
        });

        var v=browser.versions;
        function linkTargets($this){
            if(!$this.hasClass("link--dialog")){
                //普通热区
                var act=$this.attr('animation').split("_"),
                    page=$this.attr('page');
                var etIn=act[0].replace(/\-/g," ");
                var etOut=act[1].replace(/\-/g," ");
                var beforePage=$this.parents('.et-page').attr("id");
                var title;
                self._set(etIn,etOut);
                if(page){
                    if(page!="picture_-1"){
                        var $targetPage=$('#'+page);
                        title=$targetPage.attr("data-title");
                        if(!title){
                            title=$targetPage.attr("title");
                        }
                        PageTransitions.initPage($targetPage,function(){
                            $(".et-page-current").find(".link").each(function(){
                                if($(this).attr("page")=="picture_-1"){
                                    $(this).attr('history-back',beforePage);
                                }
                            });
                        });
                        if(act=="normal"||act=="tap"){
                            $targetPage.addClass("et-page-current").siblings().removeClass("et-page-current");
                        }
                        self.isRememberHistory(title);

                        $targetPage.find("img").each(function(){
                            $this.attr("src",$this.attr("ajax-src"));
                        });
                    }else{
                        var historyPage=$this.attr("history-back")||$(".et-page").eq(0).attr("id");
                        if(historyPage){
                            var $historyPage=$('#'+historyPage);
                            title=$historyPage.attr("data-title");
                            if(!title){
                                title=$historyPage.attr("title");
                            }
                            PageTransitions.initPage($historyPage,function(){
                                $(".et-page-current").find(".link").each(function(){
                                    if($(this).attr("page")=="picture_-1"){
                                        $(this).attr('history-back',beforePage);
                                    }
                                });
                            });
                            self.isRememberHistory(title);
                        }
                    }

                }else{
                    return false;
                }
            }else{
                //浮层热区
                //显示对应的浮层
                var dialogId=$this.attr("link-id");
                $this.parents(".et-wrapper").find(".dialog_box").show();
                $(".link__dialog[dialog-id='"+dialogId+"']").show();
            }
        }
        $(document).hammer().on('tap','.link',function(e){
            e.preventDefault();
            if(v.ios||v.android){
                linkTargets($(this));
            }
            return false;
        });
        $(document).on('click','.link',function(e){
            e.preventDefault();
            if(!v.ios&&!v.android){
                linkTargets($(this));
            }
            return false;
        });
    },
    dialogLinks:function(){
        var self=this;
        function dialogLinkTarget($obj){
            //普通热区

            var act=$obj.attr('animation');
            if(!act){
                act="show_hide";
            }
            act=act.split("_");
            var page=$obj.attr('target-id');
            var etIn=act[0].replace(/\-/g," ");
            var etOut=act[1].replace(/\-/g," ");
            self._set(etIn,etOut);
            if(page){
                if(page!="close"){
                    //跳转到其它页面
                    var $targetPage=$('#picture_'+page);
                    PageTransitions.initPage($targetPage,function(){
                        //隐藏所有的浮层
                        $(".dialog_box").hide();
                        $(".link__dialog").hide();
                    });
                    if(act=="normal"||act=="tap"){
                        $targetPage.addClass("et-page-current").siblings().removeClass("et-page-current");
                    }
                    var title=$targetPage.attr("data-title");
                    if(!title){
                        title=$targetPage.attr("title");
                    }

                    self.isRememberHistory(title);
                    $targetPage.find("img").each(function(){
                        $obj.attr("src",$obj.attr("ajax-src"));
                    });
                }else{
                    //关闭浮层
                    $(".dialog_box").hide();
                    $(".link__dialog").hide();
                }
            }
        }
        var v=browser.versions;
        $(document).on("touchstart",'.link__dialog__links',function(e){
            $(this).addClass("active");
        });
        $(document).on("touchend",'.link__dialog__links',function(e){
            $(this).removeClass("active");
        });
        $(document).hammer().on('tap','.link__dialog__links',function(e){
            e.preventDefault();
            var $this=$(this);
            if(v.ios||v.android){
                dialogLinkTarget($this);
            }
            return false;
        });
        $(document).on('click','.link__dialog__links',function(e){
            e.preventDefault();
            if(!v.ios&&!v.android){
                dialogLinkTarget($(this));
            }
            return false;
        });
    },
    showLinks:function(){
        var $linkBg=$("#linkBg");
        var v=browser.versions;
        $(document).on("tap",".et-page",function(e){
            if(!$(e.target).hasClass("link")){
                var $this=$(this);
                if($linkBg.length==0||$linkBg.val()==1){
                    $this.find(".link").addClass("showlink");
                }
            }
        });
        $(document).on("click",".et-page",function(e){
            if(!$(e.target).hasClass("link")){
                if(!v.ios&&!v.android) {
                    var $this = $(this);
                    if ($linkBg.length == 0 || $linkBg.val() == 1) {
                        $this.find(".link").addClass("showlink");
                    }
                }
            }
        });
        $(document).on("release",".et-page",function(e){
            var $this=$(this);
            setTimeout(function(){
                $this.find(".link").removeClass("showlink");
            },1500);
        });
    },
    _set:function(inAct,outAct){
        var $box=$('.et-wrapper');
        $box.attr({
            'et-in':inAct,
            'et-out':outAct
        });
    },
    reset:function(){
        var $box=$('.et-wrapper'),
            boxH=$(document).height(),
            user=navigator.userAgent;
        if( user.match(/Android/i)|| user.match(/iPhone/i)||user.match(/iPad/i) ){
            //$box.css({'min-height':boxH});
        }
        $box.find('img').on('mousedown mouseup',function(e){
            e.preventDefault();
        });
        PageTransitions.reset();
    },
    setPageLayer:function(){
        var self=this;
        //初始化页面
        var windowWidth=$(".et-wrapper").width();
        var windowHeight=$(".et-wrapper").height();
        var baseWidth=300;
        var zoom=windowWidth/baseWidth;
        var pzoom=320/windowWidth;

        $(".et-page").each(function(index,element){
            var $this=$(this);
            var imgWidth=$this.find(".img_box").eq(0).attr("imgwidth");
            var imgHeight=$this.find(".img_box").eq(0).attr("imgheight");
            //先加载2张图片
            if(index<2){
                $this.find("img").each(function(){
                   $(this).attr("src",$(this).attr("ajax-src"));
                });
            }
            var cutTop=$this.find(".img_box").attr("cuttop")||0;
            var cutBottom=$this.find(".img_box").attr("cutbottom")||0;
            var height=imgHeight/(imgWidth/windowWidth);

            $this.find(".cut_top").css({"height":cutTop/pzoom});
            $this.find(".cut_bottom").css({"height":cutBottom/pzoom});
            $this.find(".cut_scroll").css({"top":cutTop/pzoom,"bottom":cutBottom/pzoom});
            $this.find(".cut_scroll .inner").css({"height":height-cutTop/pzoom-cutBottom/pzoom});
            $this.find(".cut_scroll .inner img").css({"margin-top":-cutTop/pzoom});
            //设置链接热区的位置
            $this.find(".link").each(function(index){
                var $thisLink=$(this);
                var arr;
                if($thisLink.attr("base-style")){
                    arr=$thisLink.attr("base-style").split("-");
                }else{
                    arr=$thisLink.attr("basestyle").split("-");
                }
                var l=arr[0]*zoom;
                var t=arr[1]*zoom;
                var w=arr[2]*zoom;
                var h=arr[3]*zoom;
                $thisLink.css({
                    "left":l,
                    "top":t,
                    "width":w,
                    "height":h
                });
                if(t>parseInt(cutTop/pzoom)&&t<(height-parseInt(cutBottom/pzoom))-h/2){
                    $thisLink.css("top",t-parseInt(cutTop/pzoom)).appendTo($this.find(".cut_scroll .inner"));
                }
                if(t>(height-parseInt(cutBottom/pzoom))-h/2){
                    $thisLink.css({
                        "top":"auto",
                        "bottom":(height-t)-$(this).height()
                    }).attr("cut-pos","bottom");
                }
                //输出浮层
                if($thisLink.hasClass("link--dialog")){
                    var dialogImgWidth=$thisLink.attr('target-dialog-width');
                    var dialogImgHeight=$thisLink.attr('target-dialog-height');
                    var dialogImgSrc=$thisLink.attr('target-dialog-src');
                    var dialogId=$thisLink.attr("link-id");

                    //默认位置
                    var dialogPosition="middle_dialog";//正中
                    var dialogType="auto_dialog";//居中自适应
                    var _dialogHtml="";
                    var trueWidth;
                    var trueHeight;
                    if((dialogImgWidth/2)<=windowWidth){
                        trueWidth=dialogImgWidth/2;
                        trueHeight=dialogImgHeight/2;
                    }else{
                        trueWidth=windowWidth;
                        trueHeight=dialogImgHeight*(windowWidth/trueWidth);
                    }
                    var linkZoom=trueWidth/320;
                    var dosZoom;
                    if($thisLink.attr("data-link-dialog")){
                        //判断浮层内是否有链接
                        var dialogData=$thisLink.attr("data-link-dialog").replace(/\//g,'"');
                        if(dialogData) {
                            dialogData=$.parseJSON(dialogData);
                            dialogPosition=dialogData.position;
                            dialogType=dialogData.align;

                            var style;
                            if(dialogPosition=="top_dialog"){
                                if(dialogType=="all_dialog"){
                                    //通栏
                                    dosZoom=windowWidth/trueWidth;
                                    linkZoom=linkZoom*dosZoom;
                                    style="top:0;left:0;width:"+windowWidth+"px;height:"+trueHeight*dosZoom+"px;"
                                }else{
                                    //居中自适应
                                    style="top:0;left:50%;width:"+trueWidth+"px;height:"+trueHeight+"px;margin-left:-"+trueWidth/2+"px;"
                                }
                            }else if(dialogPosition=="right_dialog"){
                                if(dialogType=="all_dialog"){
                                    //通栏
                                    dosZoom=windowHeight/trueHeight;
                                    linkZoom=linkZoom*dosZoom;
                                    style="top:0;right:0;width:"+trueWidth*dosZoom+"px;height:"+windowHeight+"px;"
                                }else{
                                    //居中自适应
                                    style="top:50%;right:0;width:"+trueWidth+"px;height:"+trueHeight+"px;margin-top:-"+trueHeight/2+"px;"
                                }

                            }else if(dialogPosition=="bottom_dialog"){
                                if(dialogType=="all_dialog"){
                                    //通栏
                                    dosZoom=windowWidth/trueWidth;
                                    linkZoom=linkZoom*dosZoom;
                                    style="bottom:0;left:0;width:"+windowWidth+"px;height:"+trueHeight*dosZoom+"px;"
                                }else{
                                    //居中自适应
                                    style="bottom:0;left:50%;width:"+trueWidth+"px;height:"+trueHeight+"px;margin-left:-"+trueWidth/2+"px;"
                                }
                            }else if(dialogPosition=="left_dialog"){
                                if(dialogType=="all_dialog"){
                                    //通栏
                                    dosZoom=windowHeight/trueHeight;
                                    linkZoom=linkZoom*dosZoom;
                                    style="top:0;left:0;width:"+trueWidth*dosZoom+"px;height:"+windowHeight+"px;"
                                }else{
                                    //居中自适应
                                    style="top:50%;left:0;width:"+trueWidth+"px;height:"+trueHeight+"px;margin-top:-"+trueHeight/2+"px;"
                                }
                            }else{
                                //正中
                                if(dialogType=="all_dialog"){
                                    dosZoom=windowWidth/trueWidth;
                                    linkZoom=linkZoom*dosZoom;
                                    style="top:50%;left:0;width:"+windowWidth+"px;height:"+trueHeight*dosZoom+"px;margin-top:-"+trueHeight*dosZoom/2+"px;"
                                }else{
                                    style="top:50%;left:50%;width:"+trueWidth+"px;height:"+trueHeight+"px;margin-left:-"+trueWidth/2+"px;margin-top:-"+trueHeight/2+"px;"
                                }
                            }

                            _dialogHtml+='<div class="link__dialog" dialog-id="'+dialogId+'" style="'+style+'" >';
                            _dialogHtml+='<img style="width:100%;display:block;" src="'+dialogImgSrc+'" dialog-id="'+dialogId+'" />';
                        }
                    }else{
                        _dialogHtml+='<div class="link__dialog" dialog-id="'+dialogId+'" style="position:absolute;left:50%;top:50%;width:'+trueWidth+'px;height:'+trueHeight+'px;margin-top:'+trueHeight/2+'px;margin-left:'+trueWidth/2+'px;" >';
                        _dialogHtml+='<img style="width:100%;display:block;" src="'+dialogImgSrc+'" dialog-id="'+dialogId+'" />';
                    }
                    //输出浮层上的链接
                    if(dialogData.link){
                        $.each(dialogData.link,function(index,item){
                            _dialogHtml+='<div class="link__dialog__links" animation="show_hide" link-id="'+item.linkId+'" target-id="'+item.target+'" style="top:'+parseInt(item.top)*linkZoom+'px;left:'+parseInt(item.left)*linkZoom+'px;width:'+parseInt(item.width)*linkZoom+'px;height:'+parseInt(item.height)*linkZoom+'px;"></div>';
                        });
                    }

                    _dialogHtml+='</div>';
                    $thisLink.parents(".et-wrapper").find(".dialog_box__inner").append(_dialogHtml);
                }
            });
        });
    }
};

$(window).on("load",function(){
    var myscroll;
    var wrap=document.getElementsByClassName("cut_scroll");
    for(var i= 0,length=wrap.length;i<length;i++){
        myscroll=new IScroll(wrap[i], {
            mouseWheel: true,
            scrollbars: false
        });
    }
});

$(function(){
    window.onpopstate=function(){
        if(/ MicroMessenger\//.test(navigator.userAgent)){

        }else if(/ QQ\//.test(navigator.userAgent)){

        }else{
            pageLoadInit();
        }
    };
    function pageLoadInit(){
        var $etPage=$(".et-page");
        var defaultTitle=$etPage.eq(0).attr("data-title");
        if(!defaultTitle){
            defaultTitle=$etPage.eq(0).attr("title");
        }
        var href=window.location.href;
        var title=href.split("#")[1]||defaultTitle;
        if(title&&title!="undefined"){
            var $pageNode=$(".et-page[title='"+title+"']");
            if($pageNode.length==0){
                $pageNode=$(".et-page[data-title='"+title+"']");
            }
            var page=$pageNode.attr("id").replace("picture_","");
            demo._set('hide','show');
            var $picturePage=$("#picture_"+page);
            PageTransitions.initPage($picturePage);
            $picturePage.addClass("et-page-current").siblings().removeClass("et-page-current");
            $picturePage.find("img").each(function(){
                $(this).attr("src",$(this).attr("ajax-src"));
            });
        }
    }

    //判断是否是iphone的Safari打开
    function isSafari(){
        var standalone;
        if( typeof navigator.standalone=="boolean" && navigator.userAgent.indexOf("Safari")!= -1 && navigator.userAgent.indexOf("Version")!= -1){
            standalone=navigator.standalone;
        }else{
            standalone=true;
        }
        if(!standalone){
            $("#install_page").show();
            window.scrollTo(0,0);
        }
        $(".safari-open").click(function(){
            $(this).hide();
        });
        $("#install_page .install-app-close").click(function(){
            $("#install_page").hide();
            return false;
        });
    }

    //进入页面loading
    function loading(imgurls,imgLoading,callback) {
        var imgs=[];
        var loaded=0;
        for (var i=0;i<imgurls.length;i++) {
            imgs[i]=new Image();
            imgs[i].src=imgurls[i];
            imgs[i].onload=imgs[i].onerror=imgs[i].onabort=function () {
                loaded++;
                checkloaded();
            }
        }
        function checkloaded() {
            if(imgLoading){
                imgLoading(loaded/imgurls.length);
            }
            if (loaded==imgurls.length) {
                if (callback) {
                    callback();
                }
                imgs=null;
            }
        }
    }

    function pageLoading(){
        var img_urls=[];
        var $loading=$('.mod_loading');
        $(".et-page").each(function(){
            if($(this).index()<2){
                $(this).find(".cut_scroll").find("img").each(function(){
                    var ajax_src=$(this).attr("ajax-src");
                    img_urls.push(ajax_src);
                });
            }
        });
        //老项目无闪屏显示loading浮层
        var screenTime=$('#js_screen_time').val();
        if(!screenTime||isNaN(screenTime)){
            screenTime=0.5;
        }
        $loading.css({
            "z-index":100000,
            "display":"none"
        });
        //500毫秒内加载不完两张图片就显示加载浮层
        var timer=setTimeout(function(){
            $loading.show();
        },500);
        if(img_urls.length>0){
            //显示loading浮层
            loading(img_urls,function(val){
                $(".mod_loading__progress__bg").css('width',val*100+'%');
            },function(){
                clearTimeout(timer);
                $loading.fadeOut(500);
                var timer3=setTimeout(function(){
                    $(".app_screen").fadeOut(600);
                },screenTime*1000);
                //开始加载其它图片
                $(".et-wrapper").find("img").each(function(){
                    var ajax_src=$(this).attr("ajax-src");
                    if($(this).attr("src")==""){
                        $(this).attr("src",ajax_src);
                    }
                });
            });
        }else{
            var timer3=setTimeout(function(){
                $(".app_screen").fadeOut(600);
            },screenTime*1000);
        }
    }
   function createQrCode(){
        var arr=window.location.href.split("/");
        var date=new Date();
        var time=date.getTime();
        var url="https://"+arr[2]+"/"+arr[3]+"/"+arr[4]+"/"+arr[5]+"/"+arr[6]+"/?_wv=131076&time="+time;
        //console.info(url);
        $("#qrcode").qrcode({
            render: 'canvas',
            width: 150,
            height: 150,
            color: '#000000',
            text:url
        });
    }
    //收起侧栏
   function sidebar(){
        var side=true;
        var timer;
        timer=setTimeout(function(){
            if(side==true){
                $(".side").addClass("side--hide");
                $(this).attr("title","展开").text("展开");
                side=false;
            }
        },30000);
        $(".side-opt").click(function(){
            clearTimeout(timer);
            if(side==true){
                $(".side").addClass("side--hide");
                $(this).attr("title","展开").text("展开");
                side=false;
            }else{
                $(".side").removeClass("side--hide");
                $(this).attr("title","收起").text("收起");
                side=true;
            }
            return false;
        });
   }
    //设置手机垂直居中
    function phone_middle(){
    //平台、设备和操作系统
        var system={
            win: false,
            mac: false,
            xll: false,
            ipad:false
        };
        //检测平台
        var p=navigator.platform;
        system.win=p.indexOf("Win")==0;
        system.mac=p.indexOf("Mac")==0;
        system.x11=(p=="X11")||(p.indexOf("Linux")==0);
        system.ipad=(navigator.userAgent.match(/iPad/i) != null)?true:false;
        if (system.win||system.mac||system.xll||system.ipad) {
            var windowHeight=$(window).height();
            var phoneHeight=$(".wrap-bg").height();
            var phoneTop=parseInt($(".wrap-bg").css("top"));
            if(windowHeight>phoneHeight){
                $(".wrap").css("top",(windowHeight-phoneHeight)/2-phoneTop);
            }else{
                $("body").height(phoneHeight+parseInt($(".wrap-bg").offset().top)*2);
                $(".wrap").css("top","150px");
            }
        }
    }
    pageLoading();
    isSafari();
    sidebar();
    phone_middle();
    demo.init();
    createQrCode();
    pageLoadInit();

    var is_mobile=navigator.userAgent.toLowerCase().match(/(ipod|iphone|android|coolpad|mmp|smartphone|midp|wap|xoom|symbian|j2me|blackberry|win ce)/i) != null;
    $(window).resize(function(){
        phone_middle();
        if(is_mobile){
            console.info(is_mobile);
            demo.setPageLayer();
        }
    });
});
